package com.anti.commom.web.view;

import org.springframework.core.io.ClassPathResource;
import org.springframework.web.servlet.view.AbstractView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.util.Map;

/**
 * @Description TODO
 * @Author anTi
 * @Date 2020-11-18
 */
public class ImageView extends AbstractView {
    private String imagePath="";
    //构造方法中的 contentType 要符合 mime 规范并满足你的需求。
    public ImageView(String contentType,String imagePath) {
        setContentType(contentType);
        this.imagePath=imagePath;
    }

    @Override
    protected void renderMergedOutputModel(Map<String, Object> map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        // 模拟读取文件 并转化为文件输入流
        ClassPathResource classPathResource = new ClassPathResource(imagePath);
        FileInputStream fileInputStream = new FileInputStream(classPathResource.getFile());
        byte[] bytes = new byte[1024];
        // 利用 AbstractView 已经提供的方法 创建临时输出流
        ByteArrayOutputStream baos = super.createTemporaryOutputStream();
        int len;
        while ((len = fileInputStream.read(bytes)) != -1){
            baos.write(bytes,0,len);
        }
        // 然后把临时输出流中的数据 写入响应中
        super.writeToResponse(httpServletResponse, baos);
    }

//    使用方式
//    @GetMapping("/show")
//    public ModelAndView img() {
//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.setView(new ImageView(MimeTypeUtils.IMAGE_JPEG_VALUE,"./qr.jpg"));
//        return modelAndView;
//    }
}
